package org.jeecg.common.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.modules.sys.entity.SysAccount;
import org.jeecg.common.modules.sys.mapper.SysAccountMapper;
import org.jeecg.common.modules.sys.service.ISysAccountFlowService;
import org.jeecg.common.modules.sys.service.ISysAccountService;
import org.jeecg.common.util.enums.SysAccountFlowTypeEnum;
import org.jeecg.common.util.enums.SysAccountTypeEnum;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Objects;

/**
 * @author guoyh
 * @ClassName SysAccountServiceImpl
 * @Description
 * @since 2020/9/5 16:08
 **/
@Service
public class SysAccountServiceImpl extends ServiceImpl<SysAccountMapper, SysAccount> implements ISysAccountService {

    @Resource
    private ISysAccountFlowService sysAccountFlowService;

    @Override
    public SysAccount getOrCreateAccount(SysAccountTypeEnum accountType){
        LambdaQueryWrapper<SysAccount> query = Wrappers.lambdaQuery();
        query.eq(SysAccount::getType,accountType.getCode());
        SysAccount exits = getOne(query);
        if (Objects.isNull(exits)){
            exits = new SysAccount();
            exits.setBalance(BigDecimal.ZERO);
            exits.setName(accountType.getDesc());
            exits.setType(accountType.getCode());
            save(exits);
        }
        return exits;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void changeSysBalance(SysAccountTypeEnum accountType, SysAccountFlowTypeEnum flowType, BigDecimal amount,String relationId,String createUser){
        SysAccount account = getOrCreateAccount(accountType);
        baseMapper.changeBalance(amount,account.getId());
        sysAccountFlowService.addAccountFlow(account.getId(),flowType,amount,relationId,createUser);
    }
}
